package dnl.utils.cp;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

public class ShellEnvironment {

	public static String replaceShellVariables(String s){
		int startPos = 0;
		int pos = 0;
		String result = s;
		Set<String> vars = new HashSet<String>();
		while((pos = StringUtils.indexOf(s, "${", startPos)) != -1){
			int indexOfClosingBracket = s.indexOf("}", pos);
			String var = s.substring(pos+2, indexOfClosingBracket);
			vars.add(var);
			startPos = indexOfClosingBracket;
		}
		for (String var : vars) {
			String envVar = System.getenv(var);
			if(envVar != null){
				result = StringUtils.replace(result, "${"+var+"}", envVar);
			}
		}
		return result;
	}

}
